package com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.bumptech.glide.Glide;
import com.coffeeloversupportlibrary.R;
import com.coffeeloversupportlibrary.core.base.BaseActivity;
import com.coffeeloversupportlibrary.databinding.ShareActivityBinding;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author puyv
 * @createTime 2021/11/24 9:28
 * @projectName CoffeeLoverSupportLibrary
 * @className ShareActivity.java
 * @description TODO
 */
public class ShareActivity extends BaseActivity<ShareViewModel, ShareActivityBinding> implements
        View.OnClickListener,View.OnFocusChangeListener{

    // TODO: 2021/11/27  aliyun API 上传图片
    private OSSClient client;
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";

    //初始时 EditText 相对 NineGridView 布局参数值（px）--待做兼容性处理
    private static final int BASE_TITLE_MARGIN=450;
    private static final int BASE_CONTENT_MARGIN=500;
    private RelativeLayout.LayoutParams titleParam;
    private RelativeLayout.LayoutParams contentParam;
    // 避免初次进入时监听到焦点改变自动上滑
    private int flag=0;
    private StartSelectListener selectListener;

    @Override
    public void registerUIChangeCallBack() {

        getViewModel().getNotifyUpdate().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
               if(s.equals("success")){
                   Toast.makeText(getContext(),"分享成功即将跳转",Toast.LENGTH_SHORT).show();
                   try {
                       Thread.sleep(2000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   ShareActivity.this.finish();
               }
            }
        });

        getViewModel().getSelectPicture()
                .observe(this, new Observer<List<ImageInfo>>() {
                    @Override
                    public void onChanged(List<ImageInfo> imageInfos) {
                        // TODO: 2021/11/26 创建适配器 对布局参数动态调整 处理 addMore 控件的可见性
                        if(null!=imageInfos){
                            uiLayoutChangeFunction(imageInfos.size());
                            getBinding().gridViewAdd.setAdapter(new NineGridViewClickAdapter(getContext(),imageInfos));
                        }
                    }
                });

    }
    @Override
    public int getLayoutId() {
        return R.layout.share_activity;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // TODO: 2021/11/27   初始化 aliyun 文件直传 API
        // UpLoadFile.asyUpLoad(file,client);   ViewModel层 处理


        OSSCredentialProvider credentialProvider =
                new OSSPlainTextAKSKCredentialProvider("LTAI5tNgkcpfK7wNL7MXgkvG" ,
                        "iocrZUFJv2Nq7wbhvFvJ6WgusRAcSB");
        client=new OSSClient(getApplicationContext(), ENDPOINT, credentialProvider);


        selectListener=new StartSelectListener();
        getBinding().addShareTitle.setOnClickListener(this);
        getBinding().addShareTitle.setOnFocusChangeListener(this);
        getBinding().shareContent.setOnClickListener(this);
        getBinding().shareContent.setOnFocusChangeListener(this);
        getBinding().addMorePicture.setVisibility(View.INVISIBLE);
        titleParam=(RelativeLayout.LayoutParams) getBinding().addShareTitle.getLayoutParams();
        contentParam=(RelativeLayout.LayoutParams)getBinding().shareContent.getLayoutParams();
        getBinding().sharePhoto.setOnClickListener(selectListener);
        getBinding().addMorePicture.setOnClickListener(selectListener);
        getBinding().shareLocation.setOnClickListener(this);
        getBinding().sharePublish.setOnClickListener(this);
        //九宫格图片加载引擎
        NineGridView.setImageLoader(new ShareActivity.GlideImageLoader());

    }

    // TODO: 2021/11/26   对 EditTextView 焦点事件  点击事件监听 处理自动指定编辑时自动调整编辑框位置

    /**
    * @date 2021/11/26 14:45
    * @params [requestCode, resultCode, data]
    * @return void
    * @description TODO 通过相应编码判断处理了类型 拿到选择图片的路径数组
    */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == 101) {
                ArrayList<String> resultPaths = data.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                getViewModel().providerData(resultPaths);
                return;
            }
        } else if (RESULT_CANCELED == resultCode) {
            // TODO: 2021/11/26   取消回调  置空选择的图片
            getViewModel().clearSelectPicture();
        }
    }


    /**
    * @date 2021/11/26 14:46
    * @params
    * @return
    * @description TODO 对布局参数进行动态处理 动态适应布局
    */
    private void uiLayoutChangeFunction(@NonNull int size){
        //clear 校准450 500  320 370
        //附加功能-- 设置addMore 的可见性或者不可见行
        titleParam.topMargin=BASE_TITLE_MARGIN;
        contentParam.topMargin=BASE_CONTENT_MARGIN;
        if(size<=0){
            titleParam.topMargin+=80;
            contentParam.topMargin+=100;
            getBinding().addMorePicture.setVisibility(View.INVISIBLE);
        }else{
            // nine 扩展后的 布局微调
            titleParam.topMargin-=120;
            contentParam.topMargin-=100;
            getBinding().addMorePicture.setVisibility(View.VISIBLE);
        }
        getBinding().addShareTitle.setLayoutParams(titleParam);
        getBinding().shareContent.setLayoutParams(contentParam);
    }


    /**
    * @date 2021/11/26 14:54
    * @params [v]
    * @return void
    * @description TODO  点击监听  焦点改变监听 联合处理编辑框自动滚动效果  其他控件的处理逻辑
    */
    @Override
    public void onClick(View v) {
        if(v==getBinding().addShareTitle){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
        }else if(v==getBinding().shareContent){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
        }else if(v==getBinding().shareCancel){

        }else if(v==getBinding().shareSave){

        }else if(v==getBinding().shareHelp){

        }else if(v==getBinding().sharePublish){
             getViewModel().uploadImage(getBinding().addShareTitle.getText().toString(),
                     getBinding().shareContent.getText().toString(),client);
             Toast.makeText(getContext(),"正在上传图片请稍后...",Toast.LENGTH_SHORT).show();
        }else if(v==getBinding().shareAddWater){

        }else if (v==getBinding().shareLocation){
            startActivity(LocationServiceActivity.class);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(flag!=0){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
            flag++;
        }
    }

    /**
    * @date 2021/11/26 14:42
    * @params
    * @return
    * @description TODO  九宫格控件图片加载引擎
    */
    private class GlideImageLoader implements NineGridView.ImageLoader{

        @Override
        public void onDisplayImage(Context context, ImageView imageView, String url) {
            Glide.with(context).load(url).into(imageView);
        }
        @Override
        public Bitmap getCacheImage(String url) {
            return null;
        }
    }

    /**
    * @date 2021/11/26 15:51
    * @params
    * @return
    * @description TODO 选择分享图片的监听器
    */
    class StartSelectListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(v==getBinding().sharePhoto){
                EasyPhotos.createAlbum((Activity) getContext(), true, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.fileprovider")
                        .setPuzzleMenu(true)
                        .setCount(9)
                        .start(101);

            }else if(v==getBinding().addMorePicture){
                EasyPhotos.createAlbum((Activity) getContext(), true, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.fileprovider")
                        .setPuzzleMenu(true)
                        .setCount(9)
                        .setSelectedPhotoPaths((ArrayList<String>) reversionDataList(getViewModel().getSelectPicture().getValue()))
                        .start(101);
            }
        }
    }
    /**
    * @date 2021/11/26 16:17
    * @params [source]
    * @return java.util.List<java.lang.String>
    * @description TODO  逆转数据 ImageInfo -- String
    */
    private List<String> reversionDataList(List<ImageInfo> source){
        List<String> target=new ArrayList<String>();
        for(ImageInfo info:source){
            target.add(info.getThumbnailUrl());
        }
        return target;
    }
}
